package com.ml.doctor.view;


import android.content.Context;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;


/**
 * 倒计时控件
 */
public class CountDownTextView extends AppCompatTextView {

    private long seconds = 0;

    private MyCounter timer;

    class MyCounter extends CountDownTimer {

        public MyCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str = "验证码<font color='red'><b>" + millisUntilFinished / 1000
                    + "</b></font>s";
            CountDownTextView.this.setText(Html.fromHtml(str));
        }

        @Override
        public void onFinish() {
            CountDownTextView.this.setText("重新发送");
            timer.cancel();
            timer = null;
            CountDownTextView.this.selfSetEnabled(true);
        }
    }

    public CountDownTextView(Context context) {
        this(context, null);
    }

    public CountDownTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountDownTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        setSingleLine(true);
        setEllipsize(TextUtils.TruncateAt.END);
        setGravity(Gravity.CENTER);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    /**
     * 输入总时间单位（s）
     *
     * @param totalSeconds
     */
    public void start(long totalSeconds) {
        seconds = totalSeconds;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new MyCounter(seconds * 1000, 1000);
        timer.start();
        // 需要根据timer是否为null判断内部enabled,所以需要放在timer赋值后面
        selfSetEnabled(false);
    }

    public void stop() {
        setText("获取验证码");
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        // 需要根据timer是否为null判断内部enabled,所以需要放在timer赋值后面
        selfSetEnabled(true);
    }

    /**
     * 给外部调用的方法
     * 会同时设置标志位
     *
     * @param enabled
     */
    @Override
    public void setEnabled(boolean enabled) {
        selfSetEnabled(enabled);
    }

    /**
     * 设enable时，需要判断外部也设true且定时器为空(说明定时结束内部也是可用的)
     *
     * @param enabled
     */
    private void selfSetEnabled(boolean enabled) {
        if (enabled && timer == null) {
            super.setEnabled(true);
        } else {
            super.setEnabled(false);
        }
    }
}
